﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MebApp.Launcher.Helpers
{
    class ShortcutHelper
    {
        //steam://rungameid/570
        public static void AddShortcut(Guid appId, string appName, string fileName)
        {
            var shortcut = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            shortcut = Path.Combine(shortcut, appName + ".url");
            if (File.Exists(shortcut))
            {
                //如果快捷方式名称和ID未变更就不重建
                if (Path.GetFileNameWithoutExtension(shortcut) == appName)
                {
                    var lines = File.ReadAllLines(shortcut);
                    if (lines[5].Substring("URL=mebapp://runapp/".Length, lines[5].Length - "URL=mebapp://runapp/".Length) == appId.ToString())
                    {
                        MessageBox.Show("桌面快捷方式已存在！");
                        return;
                    }
                }
                File.Delete(shortcut);
            }
            var tpl = "[{000214A0-0000-0000-C000-000000000046}]\r\n";
            tpl += "Prop3=19,0\r\n";
            tpl += "[InternetShortcut]\r\n";
            tpl += "IDList=\r\n";
            tpl += "IconIndex=0\r\n";
            tpl += "URL=mebapp://runapp/" + appId + "\r\n";        //5
            tpl += "IconFile =" + GetIcon2(fileName) + "\r\n";
            File.WriteAllText(shortcut, tpl);
            MessageBox.Show("桌面快捷方式创建成功");
        }
        public static string GetIcon2(string fileName)
        {
            var png = AppIconHelper.GetIconByFileName(fileName, true)?.ToBitmap();
            if (png != null)
            {
                var name = Path.Combine(Path.GetDirectoryName(fileName), Path.GetFileNameWithoutExtension(fileName) + png.Width + "_" + png.Height + ".png");
                png.Save(name);
                var icoName = Path.ChangeExtension(name, "ico");
                IconHelper.ConvertToIcon(name, icoName, png.Width, false);
                return icoName;
            }
            return Path.Combine(Application.StartupPath, "meb.ico");
        }
    }
}
